package com.tianyi.wechat;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.tianyi.dao.entity.comUser.ComUser;
import com.tianyi.dao.entity.orderProducts.Orderproducts;
import com.tianyi.dao.entity.orders.Orders;
import com.tianyi.dao.entity.orders.OrdersExample;
import com.tianyi.dao.mapper.OrderproductsMapper;
import com.tianyi.dao.mapper.OrdersMapper;
import com.tianyi.dao.mapper.ProductInfoMapper;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.AddProductInfosForOrderReq;
import com.tianyi.lib.req.OrderToConfirmReq;
import com.tianyi.lib.req.QueryPage;
import com.tianyi.model.SimpleLoginUser;
import com.tianyi.util.PdfInfos;
import com.tianyi.util.PdfUtil;
import com.tianyi.util.SimpleUserUtils;
import net.coobird.thumbnailator.filters.Watermark;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * orders
 *
 * @author oh_grd
 */
@Component
public class WechatOrdersService{

    private static final Logger logger = LoggerFactory.getLogger(WeChatService.class);

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private OrderproductsMapper orderproductsMapper;

    @Autowired
    protected HttpServletRequest request;

    /**
     * 新增订单，此时订单状态为待审核/待确定，数据库中订单状态字段为to_confirm
     * @param req
     * @return
     */
    public WebResult<String> addOrder(OrderToConfirmReq req) {//JSON可用
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(req.getOrderNumber());
        ordersNeworder.setSendPerson(req.getSendPerson());
        ordersNeworder.setLendTimeDura(req.getLendTimeDura());
        ordersNeworder.setArriveTime(req.getArriveTime());
        ordersNeworder.setPhotoShootTime(req.getPhotoShootTime());
        ordersNeworder.setReceiveAddress(req.getReceiveAddress());
        ordersNeworder.setReceivePerson(req.getReceivePerson());
        ordersNeworder.setReceivePhonenumber(req.getReceivePhonenumber());
        ordersNeworder.setSendMethod(req.getSendMethod());
        ordersNeworder.setLendPerson(req.getLendPerson());
        ordersNeworder.setPhotoTheme(req.getPhotoTheme());
        ordersNeworder.setExtInfo(req.getProductInfo());
        ordersNeworder.setProductNumber(req.getProductNumber());
        ordersNeworder.setStar(req.getStar());
        ordersNeworder.setOperator(req.getOperator());
        ordersNeworder.setOrderStatus(req.getOrderStatus());
        ordersNeworder.setSendPayment(req.getSendPayment());
        ordersNeworder.setReturnTime(req.getReturnTime());
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat timeNowFormat = new SimpleDateFormat(strDateFormat);
        ordersNeworder.setLendStatus(timeNowFormat.format(date));
        SimpleLoginUser loginUser = SimpleUserUtils.getUserFromReq(request);
        if(loginUser != null) {
            ordersNeworder.setOperator(loginUser.getUserName());
        }
        ordersMapper.insert(ordersNeworder);
        return WebResult.ok("order successfully added " +req.toString());
    }

    public WebResult<String> updateOrderById(Orders order){//JSON可用
        SimpleLoginUser loginUser = SimpleUserUtils.getUserFromReq(request);
        if(loginUser != null) {
            order.setOperator(loginUser.getUserName());
        }
        Calendar calendar = Calendar.getInstance();
        order.setLendStatus(calendar.getTime().toString());
        ordersMapper.updateByPrimaryKey(order);
        return WebResult.ok("updated");
    }

    /**
     * 删除订单，根据ID将数据库中该订单信息删除
     * @param id
     * @return
     */
    public WebResult<String> deleteOrderById(Long id) {//JSON可用
        ordersMapper.deleteByPrimaryKey(id.intValue());
        return WebResult.ok("order successfully deleted");
    }

    /**
     * 按订单状态分页查询订单，把结果转成pageInfo格式返回给前端
     * @param
     * @return
     */
    public WebResult<PageInfo<Orders>> queryOrdersByStatusPageInfo(QueryPage queryPage){//JSON可用

        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderStatus(queryPage.getOrderStatus());
        List<Orders> result0 = ordersMapper.queryAllOrdersByStatus(ordersNeworder);
        if(result0.size()==0){
            return WebResult.error("数据库相应内容为空！");
        }
        Page<Orders> ordersPage = ordersMapper.queryOrdersByPageByStatusPageInfo((queryPage.getPageNo()-1)*queryPage.getPageSize(),
                queryPage.getPageSize(), queryPage.getOrderStatus());
        ordersPage.setPageNum(queryPage.getPageNo());
        ordersPage.setPageSize(queryPage.getPageSize());
        int pagesCount;
        if (result0.size()%queryPage.getPageSize() == 0){
            pagesCount = result0.size()/queryPage.getPageSize();
        }else {
            pagesCount = result0.size()/queryPage.getPageSize() +1;
        }
        if(pagesCount!=0&&(queryPage.getPageNo()<1||queryPage.getPageNo()>pagesCount)){
            return WebResult.error("超出分页查询范围");
        }
        boolean prevPage = false;
        boolean nextPage = false;
        if (queryPage.getPageNo()>1){
            prevPage = true;
        }
        if (queryPage.getPageNo()<pagesCount){
            nextPage = true;
        }

        ordersPage.setPages(pagesCount);
        ordersPage.setCount(true);
        ordersPage.setOrderBy("id ASC");
        ordersPage.setStartRow((queryPage.getPageNo()-1)*queryPage.getPageSize());
        ordersPage.setEndRow((queryPage.getPageNo()-1)*queryPage.getPageSize()+queryPage.getPageSize());
        //System.out.println("Page<Orders>： "+ordersPage.toString());
        PageInfo<Orders> ordersPageInfo = ordersPage.toPageInfo();
        ordersPageInfo.setHasPreviousPage(prevPage);
        ordersPageInfo.setHasNextPage(nextPage);
        ordersPageInfo.setTotal(result0.size());
        //System.out.println("PageInfo<Orders>： "+ordersPageInfo.toString());

        return WebResult.ok(ordersPageInfo);
    }

    /**
     * 确认订单，根据订单号将数据库中订单状态字段改为confirmed
     * @param req
     * @return
     */
    public WebResult<String> confirmOrder(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(req.getOrderNumber());
        ordersNeworder.setOrderStatus("confirmed");
        ordersMapper.updateByOrderNumber(ordersNeworder);
        return WebResult.ok("order successfully confirmed");
    }



    /**
     * 评论订单，根据订单号将数据库中该订单进行评论，评论内容字段为ext_info
     * @param req
     * @return
     */
    public WebResult<String> commentOrderById(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(req.getOrderNumber());
        ordersNeworder.setExtInfo(req.getProductInfo());
        ordersMapper.updateByPrimaryKey(ordersNeworder);
        return WebResult.ok("order successfully commented");
    }

    /**
     * 修改订单的归还状态
     * @param req
     * @return
     */
    public WebResult<String> changeLendStatusById(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(req.getOrderNumber());
        ordersNeworder.setLendStatus(req.getLendStatus());
        ordersMapper.updateByPrimaryKey(ordersNeworder);
        return WebResult.ok("order lendStatus successfully changed");
    }

    /**
     * 修改订单的订单状态
     * @param req
     * @return
     */
    public WebResult<String> changeOrderStatusById(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(req.getOrderNumber());
        ordersNeworder.setOrderStatus(req.getOrderStatus());
        ordersMapper.updateByPrimaryKey(ordersNeworder);
        return WebResult.ok("orderStatus successfully changed");
    }

    /**
     * 查询所有订单
     * @param req
     * @return
     */
    public WebResult<List<Orders>> queryAllOrders(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        List<Orders> result = ordersMapper.queryAllOrders(ordersNeworder);
        return WebResult.ok(result);
    }

    /**
     * 查询所有订单
     * @param req
     * @return
     */
    public WebResult<List<Orders>> queryAllOrdersByStatus(OrderToConfirmReq req) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderStatus(req.getOrderStatus());
        List<Orders> result = ordersMapper.queryAllOrdersByStatus(ordersNeworder);
        return WebResult.ok(result);
    }

    /**
     * 分页查询所有订单
     * @param
     * @return
     */
    public WebResult<List<Orders>> queryOrdersByPage(QueryPage queryPage){
        List<Orders> result = ordersMapper.queryOrdersByPage((queryPage.getPageNo()-1)*queryPage.getPageSize(), queryPage.getPageSize());
        return WebResult.ok(result);
    }

    /**
     * 按订单状态分页查询所有订单
     * @param
     * @return
     */
    public WebResult<List<Orders>> queryOrdersByPageByStatus(QueryPage queryPage){
        List<Orders> result = ordersMapper.queryOrdersByPageByStatus((queryPage.getPageNo()-1)*queryPage.getPageSize(),
                queryPage.getPageSize(), queryPage.getOrderStatus());
        return WebResult.ok(result);
    }


    /**
     * 根据订单的订单号来查询所借的商品信息，商品使用商品编号表示，可能不止一件，使用英文逗号分隔
     * @param
     * @return
     */
    /*
    public WebResult<List<ProductInfo>> queryProductsInfoByOrderNumber(Long orderNumber) {
        Orders ordersNeworder = new Orders();
        ordersNeworder.setOrderNumber(orderNumber);
        List<ProductInfo> resultProductInfos = new ArrayList<>();
        List<String> productNumbersResult = ordersMapper.queryProductNumbersByOrderNumber(ordersNeworder);
        for(String res : productNumbersResult) {
            System.out.println(res);
            List<ProductInfo> productInfos = productInfoMapper.selectByProductNumber(res);
            for(ProductInfo p : productInfos){
                resultProductInfos.add(p);
                System.out.println(p.toString());
            }
        }
        WebResult<List<ProductInfo>> webResult = new WebResult<>();
        webResult.setData(resultProductInfos);
        webResult.setSuccess(true);
        return webResult;
    }
    */

    /**
    * 根据订单的订单号添加借出的货号详细信息，可能不止一件，也可能不止一种颜色
    * @param
    * @return
    */
    public WebResult<String> addProductInfosForOneOrder(AddProductInfosForOrderReq req) {
        Orderproducts orderproducts = new Orderproducts();
        Calendar calendar = Calendar.getInstance();
        orderproducts.setGmtcreate(calendar.getTime());
        orderproducts.setGmtmodified(calendar.getTime());
        orderproducts.setOrdernumber(req.getOrdernumber());
        orderproducts.setProductname(req.getProductname());
        orderproducts.setReceiveaddress(req.getReceiveaddress());
        orderproducts.setPhonenumber(req.getPhonenumber());
        orderproducts.setActivity(req.getActivity());
        orderproducts.setCompanyname(req.getCompanyname());
        orderproducts.setBrandid(req.getBrandid());
        orderproducts.setPrice(req.getPrice());
        orderproducts.setInventory(req.getInventory());
        orderproducts.setUsedcount(req.getUsedcount());
        orderproducts.setColor(req.getColor());
        orderproducts.setOpenstart(req.getOpenstart());
        orderproducts.setOpenend(req.getOpenend());
        orderproducts.setBrandid(req.getBrandid());
        orderproducts.setAnnual(req.getAnnual());
        orderproducts.setQuarter(req.getQuarter());
        orderproducts.setClassifyid(req.getClassifyid());
        orderproducts.setPicture(req.getPicture());
        orderproducts.setStatus(req.getStatus());
        orderproducts.setSize(req.getSize());
        orderproducts.setProductnumber(req.getProductnumber());
        orderproducts.setTryclothestime(req.getTryclothestime());
        orderproductsMapper.insert(orderproducts);
        return WebResult.ok("order product-info successfully added");
    }

    /**
     * 根据订单的订单号返回结构化的借出的货号详细信息，可能不止一件，也可能不止一种颜色
     * @param
     * @return
     */
    /*
    public WebResult<ProductInfoOrderResult> queryProductInfosForOneOrder(long orderNumber){
        HashMap<String,Integer> colorCount = new HashMap<>();
        List<ColorPriceInventory> cargoList = new ArrayList<>();
        List<Orderproducts> productResults = orderproductsMapper.queryProductInfosForOneOrder(orderNumber);
        for(Orderproducts res : productResults){
            ColorPriceInventory colorPriceInventoryTemp = new ColorPriceInventory();
            colorPriceInventoryTemp.setColor(res.getColor());
            colorPriceInventoryTemp.setInventory(res.getInventory());
            colorPriceInventoryTemp.setPrice(res.getPrice());
            cargoList.add(colorPriceInventoryTemp);
        }
    }

     */

    /**
     * 根据订单的订单号返回借出的货号详细信息，可能不止一件，也可能不止一种颜色
     * @param
     * @return
     */
    public WebResult<List<Orderproducts>> queryProductInfosForOneOrder(long orderNumber) {
        List<Orderproducts> productResults = orderproductsMapper.queryProductInfosForOneOrder(orderNumber);
        return WebResult.ok(productResults);
    }

    /**
     * 根据订单的订单号获得借出的货号详细信息的PDF文件
     * @param
     * @return
     */
    public WebResult<String> makeProductInfosPDFForOneOrder(long orderNumber) {
        List<Orderproducts> productResults = orderproductsMapper.queryProductInfosForOneOrder(orderNumber);
        Orders order = ordersMapper.queryOrderByOrderNumber(orderNumber);
        PdfInfos pdfInfos = new PdfInfos();
        pdfInfos.setOrderNumber(order.getOrderNumber());
        pdfInfos.setLendPerson(order.getLendPerson());
        pdfInfos.setReceivePhonenumber(order.getReceivePhonenumber());
        pdfInfos.setSendMethod(order.getSendMethod());
        pdfInfos.setPhotoShootTime(order.getPhotoShootTime());
        pdfInfos.setReturnTime(order.getReturnTime());
        pdfInfos.setStar(order.getStar());
        pdfInfos.setReceiveAddress(order.getReceiveAddress());
        pdfInfos.setOperator(order.getOperator());
        pdfInfos.setPhotoTheme(order.getPhotoTheme());
        pdfInfos.setArriveTime(order.getArriveTime());

        Calendar calendar = Calendar.getInstance();
        pdfInfos.setPublishTime(calendar.getTime());

        if(productResults.size()>0) {
            pdfInfos.setCompanyname(productResults.get(0).getCompanyname());
            pdfInfos.setTryclothestime(productResults.get(0).getTryclothestime());
        }

        if(makeProductInfosToPDF(productResults, orderNumber, pdfInfos)){
            return WebResult.ok("生成的PDF文件在C盘的PDF_PATH文件夹中");
        }else{
            return  WebResult.ok("生成PDF失败");
        }
    }


    /**
     * 生成PDF文件
     * @param
     * @return
     */
    private boolean makeProductInfosToPDF(List<Orderproducts> productResults, long orderNumber, PdfInfos pdfInfos) {
        boolean tempBool1 = false;
        boolean tempBool2 = false;
        File fileDir = new File("C:\\PDF_PATH\\");
        tempBool1 = fileDir.mkdirs();
        if(!tempBool1){
            //logger.warn("the pdf file dir already existed");
        }
        String filePath = "C:\\PDF_PATH\\orderInfos"+orderNumber;
        int flag =1;
        File file = new File(filePath+".pdf");
        while(!tempBool2){
            try {
                tempBool2 = file.createNewFile();
            } catch (IOException e) {
                logger.error("error when creating a new PDF file", e);
                return false;
            }
            if(!tempBool2){
                file = new File(filePath+"-"+flag+".pdf");
                flag++;
            }
        }
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        } catch (DocumentException e) {
            logger.error("error when making orderInfos PDF", e);
        } catch (FileNotFoundException e) {
            logger.error("error when finding orderInfos PDF", e);
        }
        document.open();
        document.addAuthor("GRD");
        document.addTitle("GRD-GRD");
        document.addCreator("OH-GRD");
        try {
            PdfUtil.generatePDF(document, productResults, pdfInfos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();
        return true;
    }
}


